<template>
  <view class="app-container tenant-contract-page">
    <view class="subsection-wrapper">
      <u-subsection :list="categoriesName" :current="currentCategory" @change="sectionChange"
                    activeColor="#FF7947" fontSize="16" bold></u-subsection>
    </view>
    <mescroll-body @init="mescrollInit" top="90" @down="downCallback" @up="upCallback" class="list-wrapper">
      <view class="contract-list">
        <view class="contract-item" v-for="(item,index) in list" :key="item.id">
          <hxk-card>
            <template v-slot:header>
              <view class="header">
                <view class="title">{{ contractTypeMapping[item.contractType] }}</view>
                <view class="status">
                  <dict-tag :options="dict.type.lessee_contract_status" :value="item.lesseeContractStatus"></dict-tag>
                </view>
              </view>
            </template>
            <template v-slot:body>
              <view class="body">
                <view class="address">{{ item.premisesAddress }}</view>
                <view class="cycle">
                  租住周期：{{ item.checkInTime }} ~ {{ item.checkOutTime }}
                </view>
              </view>
            </template>
            <template v-slot:footer>
              <view class="footer">
                <view class="btn">
                  <u-button @click="viewBillList(list[index].lesseeContractId)" text="查看账单"></u-button>
                </view>
                <!-- 已签署, 已终止, 已预期 才可以删-->
                <view class="btn"
                      v-if="[CONTRACT_STATUS.SIGNED, CONTRACT_STATUS.TERMINATED, CONTRACT_STATUS.OVERDUE].includes(list[index].lesseeContractStatus)">
                  <u-button
                      @click="del(list[index].lesseeContractId)"
                      text="删除"
                      plain
                      hairline
                  ></u-button>
                </view>
                <view class="btn">
                  <u-button
                      @click="viewDetail(list[index])"
                      text="合同详情"
                      type="info"
                      plain
                      hairline
                  ></u-button>
                </view>

                <!--只有待确认才显示-->
                <view class="btn" v-if="list[index].lesseeContractStatus === CONTRACT_STATUS.WAIT_CONFIRM">
                  <u-button
                      @click="handleConfirm(list[index].lesseeContractId,list[index].contractType)"
                      text="确认合同"
                      plain
                      hairline
                  ></u-button>
                </view>

                <!--电子合同并且是签约中才显示-->
                <!--1.电子合同、2.签约中、 3.甲方未签约：partyASignFlag === '0'  -->
                <view class="btn" v-if="list[index].contractType  === CONTRACT_TYPE.ELECTRONIC && list[index].lesseeContractStatus === CONTRACT_STATUS.SIGNING && list[index].partyASignFlag === '0'">
                  <u-button
                      @click="handleSign(list[index].lesseeContractId)"
                      text="签约"
                      plain
                  ></u-button>
                </view>

<!--                </view>-->
                <!--1.电子合同、2.签约中、 3.甲方已签约：partyASignFlag === '1'  -->
                <view class="btn" v-if="list[index].contractType  === CONTRACT_TYPE.ELECTRONIC && list[index].lesseeContractStatus === CONTRACT_STATUS.SIGNING && list[index].partyASignFlag === '1'">
                  <u-button disabled text="已签约" type="info" plain></u-button>
                </view>

              </view>

            </template>
          </hxk-card>
        </view>
      </view>
    </mescroll-body>

  </view>
</template>

<script>
import {formatDateString, goto} from "@/utils/common";
import HxkCard from "@/components/hxk-card/index";
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins";
import {
  confirmTenantContract, deleteTenantContract,
  tenantContractList,
  tenantContractSigning,
  tenantEleContractPreview
} from "@/api/mine/owner";
import {CONTRACT_STATUS, CONTRACT_TYPE} from "@/components/app-constant";

export default {
  dicts: ['lessee_contract_status'],
  mixins: [MescrollMixin],
  components: {
    HxkCard
  },
  data() {
    return {
      // 1. 个人的纸质合同 2.企业纸质合同 3.个人电子合同
      categories: [
        {label: '全部', value: ''},
        {label: '纸质合同', value: ['1', '2']},
        {label: '电子合同', value: '3'}
      ],
      // 合同类型映射:1.个人纸质合同;2.企业纸质合同;3.个人电子合同;
      contractTypeMapping: {
        1: '纸质合同',
        2: '纸质合同',
        3: '电子合同'
      },
      currentCategory: 0,
      list: [],
      queryParams: {
        contractTypeList: []
      }
    };
  },
  computed: {
    CONTRACT_TYPE() {
      return CONTRACT_TYPE
    },
    CONTRACT_STATUS() {
      return CONTRACT_STATUS
    },
    categoriesName() {
      return this.categories.map(item => item.label)
    }
  },
  onLoad() {
    uni.$on('refreshData',(res) => {
      if(res.refresh){
        console.log(8888)
        //更新数据
        this.upCallback({num:this.queryParams.pageNum,size:this.queryParams.pageSize,contractTypeList:this.queryParams.contractTypeList})
      }
    })
  },
  onUnload() {
    console.log('页面卸载')
    uni.$off('refreshData')
  },
  methods: {
    formatDateString,
    upCallback(page) {
      console.log('page', page,page.contractTypeList)
      const data = {
        "pageNum": page.num,
        "pageSize": page.size,
        "contractTypeList": this.queryParams.contractTypeList
      }
      this.queryParams = {
        ...data
      }
      console.log("请求参数: " , this.queryParams)
      tenantContractList(this.queryParams).then(res => {
        this.mescroll.endBySize(res.rows.length, res.total)
        if (page.num === 1) this.list = [];
        this.list = this.list.concat(res.rows);
      }).catch(() => {
        this.mescroll.endErr();
      })
    },
    goto,
    sectionChange(index) {
      this.currentCategory = index;
      this.queryParams.contractTypeList = this.categories[index].value;
      // 再刷新列表数据
      this.mescroll.resetUpScroll()
    },
    // 查看账单
    viewBillList(lesseeContractId) {
      console.log("根据合同id查询账单: " + lesseeContractId)
      this.$tab.navigateTo('/pages/mine/other/my-contract/bill-list?lesseeContractId=' + lesseeContractId)
    },

    // 删除合同
    del(contractId) {
      this.$modal.confirm('删除后数据无法恢复，确认删除合同？').then(() => {
        deleteTenantContract(contractId).then(res => {
          this.$modal.msg('删除成功')
          this.mescroll.resetUpScroll()
        })
      })
    },
    // 查看合同详情
    viewDetail(item) {
      // 判断是电子合同还是纸质合同
      // 电子合同
      console.log(item.contractType)
      if (item.contractType === CONTRACT_TYPE.ELECTRONIC) {
        const data = {
          lesseeContractId: item.lesseeContractId,
          redirectUrl: "/pages/mine/owner/tenant-contract/list"
        }
        tenantEleContractPreview(data).then(res => {
          const url = encodeURIComponent(res.data);
          // this.$tab.navigateTo(`/pages/common/webview/index?url=${url}`)

          //跳转法大大签约页面
          this.$tab.navigateTo("/pagesFace/pages/webview/webview?url=" + url)
        })
      } else if (item.contractType === CONTRACT_TYPE.PERSONAL_PAPER || item.contractType === CONTRACT_TYPE.ENTERPRISE_PAPER) {
        this.$tab.navigateTo('/pages/mine/owner/tenant-contract/detail?id=' + item.lesseeContractId)
      }

    },
    // 确认租客合同
    handleConfirm(contractId,type) {
      if(type === CONTRACT_TYPE.ELECTRONIC){
        this.$modal.confirm('确认合同信息无误？').then(() => {
          confirmTenantContract(contractId).then(res => {
            this.$modal.msg('确认成功')
            this.mescroll.resetUpScroll()
          })
        })
      }else if(type === CONTRACT_TYPE.PERSONAL_PAPER || type === CONTRACT_TYPE.ENTERPRISE_PAPER){
        // 跳转确认页面
        // 通道更新
        this.$tab.navigateTo('/pages/mine/owner/tenant-contract/confirm-contract?id=' + contractId)
      }

    },
    // 签约
    handleSign(contractId) {
      this.$modal.confirm('确定签约此合同吗？').then(() => {
        const data = {
          lesseeContractId: contractId,
          redirectUrl: '/pages/mine/owner/tenant-contract/list'
        }
        console.log("签约: " + data)
        tenantContractSigning(data).then(res => {
          // console.log(res)
          // this.$modal.msg('签约成功')
          // this.$tab.navigateTo(`/pages/common/webview/index?url=${encodeURIComponent(res.data)}`)

          const url = encodeURIComponent(res.data);
          //跳转法大大签约页面
          this.$tab.navigateTo("/pagesFace/pages/webview/webview?url=" + url)
        })
      })
    }
  }
}
</script>

<style lang="scss">
.tenant-contract-page {
  .subsection-wrapper {
    padding: 0 20rpx;
    z-index: 9990;
    position: fixed;
    padding-top: 20rpx;
    left: 0;
    width: 100%;
    height: 100rpx;
    box-sizing: border-box;
    //background-color: #F1F1F1;
  }

  .contract-list {
    padding: 20rpx;

    .contract-item {
      margin-bottom: 20rpx;

      .header {
        display: flex;
        justify-content: space-between;

        .title {
          font-size: 32rpx;
          color: #111;
        }

        .status {
          font-size: 28rpx;

          &.pending {
            color: #f29100;
          }

          &.confirmed {
            color: #18b566;
          }

        }
      }

      .body {
        .cycle {
          font-size: 28rpx;
          color: #666;
          margin-top: 20rpx;
        }

        .address {
          font-size: 28rpx;
          color: #666;
          margin-top: 20rpx;
        }


      }

      .footer {
        display: flex;
        justify-content: flex-end;

        .btn {
          padding: 0 20rpx;
          font-size: 28rpx;
          .u-button--info {
            border: none !important;
            color: #000000;
          }
        }
      }

    }
  }
}

</style>
